package com.ruoyi.terminal.service.impl;

import com.ruoyi.terminal.domain.DcSim;
import com.ruoyi.terminal.domain.SimResponse.Balance.BalanceResponse;
import com.ruoyi.terminal.domain.SimResponse.Balance.BalanceResult;
import com.ruoyi.terminal.domain.SimResponse.BasicInfo.BasicInfoResponse;
import com.ruoyi.terminal.domain.SimResponse.BasicInfo.BasicInfoResult;
import com.ruoyi.terminal.domain.SimResponse.Data.DataResponse;
import com.ruoyi.terminal.domain.SimResponse.Data.DataResult;
import com.ruoyi.terminal.domain.SimResponse.Token.TokenResponse;
import com.ruoyi.terminal.domain.SimResponse.Token.TokenResult;
import com.ruoyi.terminal.mapper.DcSimMapper;
import com.ruoyi.terminal.service.IDcSimService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * sim卡管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-01-08
 */
@Service
public class DcSimServiceImpl implements IDcSimService 
{
    @Autowired
    private DcSimMapper dcSimMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询sim卡管理
     * 
     * @param IccidImei sim卡管理ID
     * @return sim卡管理
     */
    @Override
    public DcSim selectDcSimById(String IccidImei)
    {
        return dcSimMapper.selectDcSimById(IccidImei);
    }

    /**
     * 查询sim卡管理列表
     * 
     * @param dcSim sim卡管理
     * @return sim卡管理
     */
    @Override
    public List<DcSim> selectDcSimList(DcSim dcSim)
    {
        return dcSimMapper.selectDcSimList(dcSim);
    }

    /**
     * 新增sim卡管理
     * 
     * @param dcSim sim卡管理
     * @return 结果
     */
    @Override
    public int insertDcSim(DcSim dcSim)
    {
        dcSim.setGmtCreate(new Date());
        dcSim.setGmtModified(new Date());
        return dcSimMapper.insertDcSim(dcSim);
    }

    /**
     * 修改sim卡管理
     * 
     * @param dcSim sim卡管理
     * @return 结果
     */
    @Override
    public int updateDcSim(DcSim dcSim)
    {
        dcSim.setGmtModified(new Date());
        return dcSimMapper.updateDcSim(dcSim);
    }

    /**
     * 批量删除sim卡管理
     * 
     * @param simIccids 需要删除的sim卡管理ID
     * @return 结果
     */
    @Override
    public int deleteDcSimByIds(String[] simIccids)
    {
        return dcSimMapper.deleteDcSimByIds(simIccids);
    }

    /**
     * 删除sim卡管理信息
     * 
     * @param simIccid sim卡管理ID
     * @return 结果
     */
    @Override
    public int deleteDcSimById(String simIccid)
    {
        return dcSimMapper.deleteDcSimById(simIccid);
    }

    /**
     * 获取token
     *
     * @return token
     */
    @Override
    public String getToken() {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");

        String key = "token";
        String value = "";
        String api = "https://api.iot.10086.cn/v5/ec/get/token?";
        String appid = "731210925731731000";
        String pwd = "xo9fv5NP6";

        if(redisTemplate.opsForValue().get(key) == null) {
            Date now = new Date();
            String nowString = dateFormat.format(now);
            String random = RandomStringUtils.random(8, false, true);
            String transid = appid + nowString + random;
            String url = api + "appid=" + appid + "&password=" + pwd + "&transid=" + transid;

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<TokenResponse> tokenResponseEntity = restTemplate.getForEntity(url, TokenResponse.class);
            List<TokenResult> tokenResult = tokenResponseEntity.getBody().getResult();
            value = tokenResult.get(0).getToken();

            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, 3600, TimeUnit.SECONDS);

        }
        else {
            value = (String) redisTemplate.opsForValue().get(key);
        }
        return value;
    }


    /**
     * 获取sim卡信息
     *
     * @param simIccid
     * @return
     */
    public DcSim refreshSim(String simIccid) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        DcSim dcSim = dcSimMapper.selectDcSimById(simIccid);

        String token = getToken();
        String appid = "731210925731731000";
        String basicInfoApi = "https://api.iot.10086.cn/v5/ec/query/sim-basic-info?";
        String balanceApi = "https://api.iot.10086.cn/v5/ec/query/balance-info?";
        String dataApi = "https://api.iot.10086.cn/v5/ec/query/sim-data-usage?";

        Date now = new Date();
        String nowString = dateFormat.format(now);
        String random = RandomStringUtils.random(8, false, true);

        if(token != null)
        {
            String transid = appid + nowString + random;
            String basicInfoUrl = basicInfoApi + "transid=" + transid + "&token=" + token + "&iccid=" + simIccid;
            String balanceUrl = balanceApi + "transid=" + transid + "&token=" + token + "&iccid=" + simIccid;
            String dataUrl = dataApi + "transid=" + transid + "&token=" + token + "&iccid=" + simIccid;

            RestTemplate restTemplate = new RestTemplate();

            ResponseEntity<BasicInfoResponse> basicInfoResponseEntity = restTemplate.getForEntity(basicInfoUrl, BasicInfoResponse.class);
            List<BasicInfoResult> basicInfoResult = basicInfoResponseEntity.getBody().getResult();
            String msisdn = basicInfoResult.get(0).getMsisdn();
            String imsi = basicInfoResult.get(0).getImsi();
            Date open = basicInfoResult.get(0).getOpenDate();
            Date active = basicInfoResult.get(0).getActiveDate();

            ResponseEntity<BalanceResponse> balanceResponseEntity = restTemplate.getForEntity(balanceUrl, BalanceResponse.class);
            List<BalanceResult> balanceResult = balanceResponseEntity.getBody().getResult();
            Double balance = balanceResult.get(0).getAmount();

            ResponseEntity<DataResponse> dataResponseEntity = restTemplate.getForEntity(dataUrl, DataResponse.class);
            List<DataResult> dataResult = dataResponseEntity.getBody().getResult();
            Double flowUsed = (dataResult.get(0).getDataAmount())/1024; //返回的是KB，转换成MB

            dcSim.setSimMsisdn(msisdn);
            dcSim.setSimImsi(imsi);
            dcSim.setSimOpenDate(open);
            dcSim.setSimActiveDate(active);
            dcSim.setSimAcctBal(balance);
            dcSim.setSimFlowUsedM(Math.round(flowUsed * 1000) / 1000.0); //保留三位小数
//            dcSim.setGmtModified(new Date());

        }
        return dcSim;
    }

}
